package com.witmore.neutron.ai.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jk.common.response.ResponseResult;
import com.jk.common.utils.JwtUtil;
import com.jk.common.utils.PasswordUtil;
import com.witmore.neutron.ai.db.entity.UserDO;
import com.witmore.neutron.ai.db.mapper.UserMapper;
import com.witmore.neutron.ai.web.controller.vo.LoginParam;
import com.witmore.neutron.ai.web.controller.vo.UserSession;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * Description: LoginController
 * Author: 豆子高
 * Date: 2025/5/15 15:03
 */
@Controller
@RequestMapping("")
public class LoginController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtUtil jwtUtil;


    // ################################################# 页面 相关 #################################################
    /**
     * 登录页面
     */
    @RequestMapping("/login")
    public String index() {
        return "login";
    }

    /**
     * 验证码登录页面
     */
    @RequestMapping("/login/sms")
    public String smsLogin() {
        return "sms-login";
    }


    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    public String logout(HttpServletResponse response) {
        // 清除 Cookie 中的 Token
        Cookie tokenCookie = new Cookie("Authorization", null);
        tokenCookie.setPath("/");
        tokenCookie.setHttpOnly(true);
        // 立即过期
        tokenCookie.setMaxAge(0);
        response.addCookie(tokenCookie);
        // 重定向到登录页面
        return "redirect:/login";
    }
    // ################################################# 接口 相关 #################################################
    @ResponseBody
    @PostMapping("/loginCheck")
    public ResponseResult<UserSession> processLogin(@RequestBody LoginParam loginParam, HttpServletResponse response) {
        // 校验参数
        if (loginParam == null || StringUtils.isEmpty(loginParam.getUsername()) || StringUtils.isEmpty(loginParam.getPassword())) {
            return ResponseResult.fail(400, "用户名或密码不能为空");
        }
        UserDO userDO = userMapper.selectOne(new LambdaQueryWrapper<UserDO>()
                .eq(UserDO::getUserName, loginParam.getUsername())
        );
        if (userDO == null) {
            return ResponseResult.fail(401, "登录失败，用户不存在");
        }
        // 验证密码
        boolean checkedPassword = PasswordUtil.checkPassword(loginParam.getPassword(), userDO.getPassword());
        if (!checkedPassword) {
            return ResponseResult.fail(401, "登录失败，密码错误");
        }
        UserSession userSession = new UserSession();
        BeanUtils.copyProperties(userDO, userSession);
        // 生成 JWT Token
        String token = jwtUtil.generateToken(JSONObject.toJSONString(userSession));
        token = URLEncoder.encode(token, StandardCharsets.UTF_8);
        // 创建 Cookie 存储 Token
        Cookie tokenCookie = new Cookie("Authorization", token);
        // 整个应用有效
        tokenCookie.setPath("/");
        // 防止 XSS
        tokenCookie.setHttpOnly(true);
        // 有效期 24 小时
        tokenCookie.setMaxAge(3600 * 24);
        response.addCookie(tokenCookie);

        userSession.setToken(token);
        // 移除硬编码的重定向地址，由前端处理重定向逻辑
        return ResponseResult.success(userSession);
    }


}
